//
//  DietNewsViewController.m
//  Menu
//
//  Created by YouLu on 15/7/1.
//  Copyright (c) 2015年 lijiangang. All rights reserved.
//

#import "DietNewsViewController.h"

@interface DietNewsViewController ()

@end

@implementation DietNewsViewController

- (void)dealloc
{
    [_caudleKindTableView release];
    [_caudleCollectionView release];
    [_caudleKindsArray release];
    [_caudleItemArray release];
    [_url release];
    [_HUD release];
    [super dealloc];
}

-(void)viewWillAppear:(BOOL)animated
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@"3" forKey:@"number"];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"粥&汤";
    self.automaticallyAdjustsScrollViewInsets = NO;
//tableView------------------------------------------------------

    self.caudleKindTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, 125*WIDTH, MyHeight- 49 - 64)];
    self.view.backgroundColor = [UIColor whiteColor];
    self.caudleKindTableView.backgroundColor = [UIColor clearColor];
    UIImageView *tableImgV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"caudleBgImg.png"]];
    self.caudleKindTableView.backgroundView = tableImgV;
    self.caudleKindTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.caudleKindTableView];
    self.caudleKindTableView.delegate = self;
    self.caudleKindTableView.dataSource = self;
    
//collectionView---------------------------------------------------
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.caudleCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(125*WIDTH, 64, 250*WIDTH, MyHeight- 49 - 64) collectionViewLayout:flowLayout];
    flowLayout.itemSize = CGSizeMake(100*WIDTH, 140*HEIGHT);
    //头部区域视图大小
    //flowLayout.headerReferenceSize = CGSizeMake(250*WIDTH, 74*HEIGHT);
    //底部区域视图大小
    //flowLayout.footerReferenceSize = CGSizeMake(250*WIDTH, 10*HEIGHT);
    //滑动方向默认竖直滑动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //边框宽度
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
    //列间距
    flowLayout.minimumInteritemSpacing = 10;
    //行间距
    flowLayout.minimumLineSpacing = 10;
    
    self.caudleCollectionView.backgroundColor = [UIColor whiteColor];
    UIImageView *collectImageV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"caudleBgImg.png"]];
    self.caudleCollectionView.backgroundView = collectImageV;
    [self.view addSubview:self.caudleCollectionView];
    self.caudleCollectionView.delegate = self;
    self.caudleCollectionView.dataSource = self;
    
    //注册cell
    [self.caudleCollectionView registerClass:[CaudleCollectionViewCell class] forCellWithReuseIdentifier:@"caudleItem"];
    //注册头部区域
    [self.caudleCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"caudleHeader"];
    //注册底部区域
    [self.caudleCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"caudleFooter"];
    
    self.caudleKindsArray = [NSMutableArray array];
    self.caudleItemArray = [NSMutableArray array];
    
    [[DataHandle shareData] openDataBase];
//    [[DataHandle shareData] dropCaudleCacheTable];
//    [[DataHandle shareData] dropCaudleListCacheTable];
    [[DataHandle shareData] createCaudleCacheTable];
    [[DataHandle shareData] createCaudleListCacheTable];
    
    self.caudleKindsArray = [[DataHandle shareData] selectCaudleListCacheTable];
    [self.caudleKindsArray removeLastObject];
    self.caudleItemArray = [[DataHandle shareData] selectCaudleCacheTable:@"43"];
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"loading";
    [self.HUD show:YES];
    

//AFN请求tableView数据------------------------------------------------
    [AFNTool get:@"http://121.41.117.95:80/HandheldKitchen/api/more/hotwater!getHotwaterClass.do?is_traditional=0" Body:nil HttpResult:JSON success:^(id result)
    {
        [[DataHandle shareData] dropCaudleListCacheTable];
        [[DataHandle shareData] createCaudleListCacheTable];
        [self.caudleKindsArray removeAllObjects];
        NSMutableDictionary *bigDict = result;
        NSMutableArray *bigArray = [bigDict objectForKey:@"data"];
        for (NSMutableDictionary *kindsDict in bigArray)
        {
            CaudleModel *caudle = [[CaudleModel alloc] init];
            caudle.caudleKinds = [kindsDict objectForKey:@"name"];
            caudle.typeId = [kindsDict objectForKey:@"id"];
            [self.caudleKindsArray addObject:caudle];
            [[DataHandle shareData] insertCaudleListCacheTable:caudle];
            [caudle release];
        }
        [self.caudleKindsArray removeLastObject];
        
        [self.caudleKindTableView reloadData];
        [self.HUD hide:YES];
    }
    failure:^(NSError *error)
    {
        self.HUD.labelText = @"加载失败";
        [self.HUD hide:YES afterDelay:1];
    }];
//--------------------------------------------------------------------
//AFN请求collectionView数据
    self.pageNum = 1;
    
    self.typeId = 43;
    
    [self loadAllData:self.typeId page:self.pageNum];
    [self.caudleCollectionView addLegendFooterWithRefreshingBlock:^{
        self.pageNum++;
        [self loadAllData:self.typeId page:self.pageNum];
        [self.caudleCollectionView reloadData];
        [self.caudleCollectionView.footer endRefreshing];
        [self.HUD hide:YES];
        if (self.pageNum > self.maxPageNum)
        {
            [self.caudleCollectionView.footer noticeNoMoreData];
        }
    }];
    [tableImgV release];
    [collectImageV release];
    [flowLayout release];
    [_caudleKindTableView release];
    [_caudleCollectionView release];
}


-(void)loadAllData:(NSInteger)typeId page:(NSInteger)page
{
    NSString *strUrl = [NSString stringWithFormat:@"http://121.41.117.95:80/HandheldKitchen/api/more/hotwater!getHotwaterList.do?id=%ld&page=%ld&pageRecord=8&is_traditional=0",typeId,page];
    [AFNTool get:strUrl Body:nil HttpResult:JSON success:^(id result) {
        if (page == 1) {
            
            [self.caudleItemArray removeAllObjects];
            [[DataHandle shareData] createCaudleCacheTable];
            [[DataHandle shareData] deleteCaudleCacheTable:[NSString stringWithFormat:@"%ld",typeId]];
        }
        NSMutableDictionary *bigDict = result;
        NSMutableDictionary *theDic = [result objectForKey:@"bean"];
        self.maxPageNum = [[theDic objectForKey:@"maxPageNumber"] integerValue];
        NSMutableArray *bigArray = [bigDict objectForKey:@"data"];
        for (NSMutableDictionary *dict in bigArray)
        {
            CaudleModel *caudle = [[CaudleModel alloc] initWithDic:dict];
            caudle.caudleId = [dict objectForKey:@"id"];
            caudle.typeId = [NSString stringWithFormat:@"%ld", typeId];
            [self.caudleItemArray addObject:caudle];
            [[DataHandle shareData] insertCaudleCacheTable: caudle];
            [caudle release];
        }
        self.netOK = YES;
        [self.caudleCollectionView reloadData];
        [self.HUD hide:YES];
    }
    failure:^(NSError *error)
    {
        self.HUD.labelText = @"加载失败";
        [self.HUD hide:YES afterDelay:1];
    }];
}

//tableView协议方法----------------------------------------------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.caudleKindsArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellMark = @"theCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellMark];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellMark] autorelease];
    }
    cell.contentView.backgroundColor = [UIColor whiteColor];
    cell.contentView.alpha = 0.5;
    cell.backgroundColor = [UIColor clearColor];
    CaudleModel *caudle = [self.caudleKindsArray objectAtIndex:indexPath.section];
    cell.textLabel.text = caudle.caudleKinds;
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.textLabel.textColor = [UIColor blackColor];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"loading";
    [self.HUD show:YES];
//    [self.caudleItemArray removeAllObjects];
    self.pageNum = 1;
    CaudleModel *caudle = [self.caudleKindsArray objectAtIndex:indexPath.section];
    self.typeId = [caudle.typeId integerValue];
    [self loadAllData:self.typeId page:self.pageNum];
    [self.caudleCollectionView.footer resetNoMoreData];
    [[DataHandle shareData] openDataBase];
    self.caudleItemArray = [[DataHandle shareData] selectCaudleCacheTable:caudle.typeId];
    
    [self.caudleCollectionView reloadData];
}

//collectionView协议方法-------------------------------------------
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.caudleItemArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //直接从系统的重用池里取cell
    CaudleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"caudleItem" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    cell.caudleModel = [self.caudleItemArray objectAtIndex:indexPath.item];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (!self.netOK) {
        
        self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.HUD.labelText = @"请求失败";
        [self.HUD show:YES];
        [self.HUD hide:YES afterDelay:0.5];
        return;
    }
    PayFoodViewController *payFoodVC = [[PayFoodViewController alloc] init];
    CaudleModel *caudleModel = [self.caudleItemArray objectAtIndex:indexPath.item];
    payFoodVC.payFoodName = caudleModel.name;
    payFoodVC.payFoodId = caudleModel.caudleId;
    [self.navigationController pushViewController:payFoodVC animated:YES];
    [payFoodVC release];
    NSLog(@"item");
}

-(void)pushToCollectController
{
    CollectViewController *collectVC = [[CollectViewController alloc] init];
    [self.navigationController pushViewController:collectVC animated:YES];
    [collectVC release];
}

-(void)pushToEssentialController
{
    EssentialViewController *essentialVC = [[EssentialViewController alloc] init];
    [self.navigationController pushViewController:essentialVC animated:YES];
    [essentialVC release];
}

-(void)pushToRandomController
{
    RandomViewController *randomVC = [[RandomViewController alloc] init];
    [self.navigationController pushViewController:randomVC animated:YES];
    [randomVC release];
}



































- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
